<?php

namespace Pig\Controller;
use \Pig\Util\Page;
trait Common{
	/**
     * 列表页面
     */
    public function index() {
        $this->init(); //加载初始化数据
        $Obj = D($this->tbName); //实例化对象

        $Where = "deleted=0";
        
        if(I('post.limit_num') != ''){
            session('page_limit_num', I('post.limit_num'));
        }
        $sorting = I('get.sorting') ? I('get.sorting') : 'id';
        $order = I('get.order') ? I('get.order') : 'desc';
        $limit_num = $_SESSION['page_limit_num'] ? $_SESSION['page_limit_num'] : 10;
        
        $Page = new Page($Obj->where($Where)->count(), $limit_num); // 实例化分页类 传入总记录数和每页显示的记录数
        $list = $Obj->where($Where)->order($sorting . ' ' . $order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        if($list && array_key_exists('image', $list[0])){
            foreach ($list as $key => &$value) {
                $value['image'] = C('PATH_UPLOAD').CONTROLLER_NAME.'/'.date('Ym',$value['crdate']).'/'.$value['image'];
            }
        }
        $this->assign('list', $list); // 赋值数据集
        $this->assign('page', $Page->show()); // 分页显示输出 
        $this->display('Common/index'); // 输出模板
    }

    /**
     * 编辑数据
     */
    public function edit() {
        $this->save();
    }
    /**
     * 保存数据
     */
    public function save() {
        try{
            $this->init();
            //编辑数据
            $id = I('request.id') ? I('request.id') : null;
            $info = M($this->tbName)->where('id = ' . $id)->find();
            if (IS_POST) {
                foreach ($_POST as $key => $val) {
                	if(@$this->tca[$key]['required'] && !preg_match('/\S/', $val)){
                		$this->error($this->tca[$key]['label'] . '*是必填项!');
                	}
                    //数据验证
                    if(isset($this->tca[$key]['validate'])){
                        //是否存在关联数据
                        if(isset($this->tca[$key]['relation'])){
                            //判断关联数据值类型 进入不同的判断表达式 只支持字符串，数组两种类型
                            if(is_array($this->tca[$key]['relation'][1])){
                                if(in_array($_POST[$this->tca[$key]['relation'][0]],$this->tca[$key]['relation'][1])){
                                    foreach ($this->tca[$key]['validate'] as $value) {
                                        if(!preg_match($value[0], $val)){
                                            $this->error($value[1]);
                                        }
                                    }
                                }
                            }else{
                                if($_POST[$this->tca[$key]['relation'][0]] == $this->tca[$key]['relation'][1]){
                                    foreach ($this->tca[$key]['validate'] as $value) {
                                        if(!preg_match($value[0], $val)){
                                            $this->error($value[1]);
                                        }
                                    }
                                }
                            }
                        }else{
                            foreach ($this->tca[$key]['validate'] as $value) {
                                if(!preg_match($value[0], $val)){
                                    $this->error($value[1]);
                                }
                            }
                        }
                    }
                }
                //删除文件 begin **********************************
                $path = $this->Config['path_upload'] . CONTROLLER_NAME . '/';
                $save_path = ''; // 设置附件上传目录
                $extent_path = ($info['crdate'] ? date('Ym', $info['crdate']) : date('Ym')) . '/';
                if ($info && $info['image'] && $_POST['delete_image'] == '1') {
                    if ($this->thumb_width) {
                        $thumb_path = $path.$save_path.'thumb_0/'.  $extent_path;
                        $this->delInfoFile($thumb_path, $info['image']);
                    }

                    $file_path = $path.$save_path.$extent_path;
                    $this->delInfoFile($file_path, $info['image']);
                } else {
                    unset($_POST['image']);
                }
                //删除文件 end **********************************
                
                //文件上传 begin **********************************
                if (count($_FILES) && isset($_FILES['image'])) {
                    $thumb_width = $this->thumb_width;
                    $thumb_height = $this->thumb_height;
                    $upload = $this->uploadFile('image', $path, $save_path, $extent_path, $thumb_width, $thumb_height);

                    if (is_array($upload) && $upload['upload']) {
                        $_POST['image'] = $upload['info'];
                    } else {
                        $this->error($upload['info']);
                    }
                }
                //文件上传 end **********************************
                $Obj = D($this->tbName);
                $result = $Obj->create();
                if (!$result) {
                    $this->error($Obj->getError());
                } else {        
                    if ($id) {
                        $Obj->tstamp = time();
                        $id = $Obj->where(array('id' => $id))->save();
                        $message = '编辑成功!';
                    } else {
                        $Obj->crdate = time();
                        $Obj->tstamp = time();
                        $id = $Obj->add();
                        $message = '添加成功!';
                    }
                    if($id){
                    	$this->success($message, U(CONTROLLER_NAME . '/index', 'kept=1'));
                    	exit;
                    }else{
                    	debug($Obj->_sql());
                    	$this->error('保存失败');
                    	exit;
                    }
                    
                }
            }
            $Base = New BaseController();
            //自动渲染字段
            $Base->autoFields($this->tca, $info);
            $this->display('Common/info');
        }catch(\Exception $e){
            debug($e->getmessage());
            //判断是否有文件上传
            if(count($_FILES)){
                $extent_path = ($info['crdate'] ? date('Ym', $info['crdate']) : date('Ym')) . '/';
                $file_path = $path . $extent_path;
                if(is_file($file_path.$upload['info'])){
                    $this->delInfoFile($file_path, $upload['info']);
                    if ($this->thumb_width) {
                        $thumb_path = $path.'thumb_0/'. $extent_path;
                        $this->delInfoFile($thumb_path, $info['image']);
                    }
                }
            }
            $message = IS_AJAX?'保存失败':'';
            $this->error($message);
        }
    }
}